package com.elitesland.demo.controller;

import com.elitesland.security.service.entity.JwtUserDto;
import com.elitesland.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;

import java.util.Optional;

/**
 * .
 *
 * @author Kaiser（wang shao）
 * @date 2021-02-22
 */
public abstract class BaseController {

    protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private SysUserService sysUserService;


    /**
     * 获取当前用户信息
     * <p>
     * 用于管理端
     *
     * @return 用户信息
     */
    protected JwtUserDto currentUser() {
        return currentUser(false);
    }

    /**
     * 获取当前用户
     *
     * @param required 是否必须，如果为true，当用户没有登录，则抛异常
     * @return 用户信息
     */
    protected JwtUserDto currentUser(boolean required) {
        Optional<JwtUserDto> optionalUser = sysUserService.current();
        if (optionalUser.isEmpty() && required) {
            throw new AccessDeniedException("无权限");
        }
        return optionalUser.orElse(null);
    }
}
